package demo.kk;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

// 自定义一个简单的互斥锁
public class SimpleMutexLock {
    private final Sync sync = new Sync();
    
    // 内部同步器类
    private static class Sync extends AbstractQueuedSynchronizer {
        // 尝试获取锁
        @Override
        protected boolean tryAcquire(int arg) {
            // 使用CAS操作将state从0改为1
            if (compareAndSetState(0, 1)) {
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }
        
        // 尝试释放锁
        @Override
        protected boolean tryRelease(int arg) {
            if (getState() == 0) {
                throw new IllegalMonitorStateException();
            }
            setExclusiveOwnerThread(null);
            setState(0); // 不需要CAS，因为只有持有锁的线程才能释放
            return true;
        }
        
        // 判断是否处于占用状态
        @Override
        protected boolean isHeldExclusively() {
            return getState() == 1;
        }
    }
    
    // 加锁
    public void lock() {
        sync.acquire(1);
    }
    
    // 解锁
    public void unlock() {
        sync.release(1);
    }
    
    // 测试
    public static void main(String[] args) {
        SimpleMutexLock lock = new SimpleMutexLock();
        final int[] count = {0};
        
        // 创建多个线程测试锁
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                lock.lock();
                try {
                    for (int j = 0; j < 1000; j++) {
                        count[0]++;
                    }
                    System.out.println(Thread.currentThread().getName() + " 完成计数");
                } finally {
                    lock.unlock();
                }
            }).start();
        }
        
        try {
            Thread.sleep(2000); // 等待所有线程完成
            System.out.println("最终结果: " + count[0]); // 应该是10000
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}